#include "adc.h"
#include "bsp_uart.h"
#include "infrared.h"
#include "w55mh32_gpio.h"
#include "w55mh32_rcc.h"
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

/**
 * @brief Initialize infrared sensor (configure PA3 as analog input mode)
 * @note Infrared sensor connected to PA3, multiplexed as ADC input channel 3
 */
void infrared_init(void) {
  GPIO_InitTypeDef gpio_init_structure;
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); // Enable GPIOA clock

  // Configure PA3 as analog input (for reading analog signal from infrared
  // sensor)
  gpio_init_structure.GPIO_Pin = GPIO_Pin_3;
  gpio_init_structure.GPIO_Mode = GPIO_Mode_AIN; // Analog input mode
  GPIO_Init(GPIOA, &gpio_init_structure);
}

/**
 * @brief Get infrared sensor detection result (based on filtered AD value)
 * @return 1-detected object (AD value<1500), 0-no object detected (AD
 * value≥1500)
 * @note Depends on ADC module's filtering function (AD_FilterProcess), ADC must
 * be initialized first
 */
uint16_t infrared_get_data(void) {
  uint16_t temp_data;
  uint16_t temp;

  ad_filter_process();           // Execute AD filtering to get stable value
  temp = g_ad_filtered_value[0]; // Filtered value of ADC channel 0
                                 // corresponding to infrared sensor

  // Determine if object is detected based on threshold
  if (temp < 1500) {
    temp_data = 1; // Object detected
  } else {
    temp_data = 0; // No object detected
  }

  return temp_data;
}

/**
 * @brief Read raw AD value from infrared sensor (unfiltered)
 * @return Raw AD sampling value (directly taken from ADC raw buffer)
 */
uint16_t infrared_read_raw(void) {
  return g_ad_value[0]; // Raw value of ADC channel 0 corresponding to infrared
                        // sensor
}
